#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <string>
using namespace std;

#define NUM 3
// int *p = nullptr;
// __thread unsigned long int tid = 0;
// __thread pid_t pid = 0;
__thread int number = 0;
class threadData
{
public:
    threadData(const string &s)
        : pthreadname(s)
    {
    }

public:
    string pthreadname;
};
string tohax(pthread_t tid)
{
    char buff[128];
    snprintf(buff, sizeof(buff), "%p", tid);
    return buff;
}
void *threadroutine(void *args)
{
    pthread_detach(pthread_self());
    int a = 0;

    threadData *td = static_cast<threadData *>(args);
    // if (td->pthreadname == "thread-2")
    // p = &a;
    // pid = getpid();
    // tid = pthread_self();
    int cnt = 5;
    while (cnt)
    {
        cout << "pid:" << getpid()
             << ", tid:" << tohax(pthread_self())
             << ", pthreadname:" << td->pthreadname
             << ", a:" << a << ",&a:" << &a << ", number:" << number << ", &number:" << &number << endl;
        sleep(1);
        cnt--, a++, number++;
    }
    delete td;
    return nullptr;
}
int main()
{
    vector<pthread_t> tids;
    for (int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        string s = "thread-" + to_string(i);
        threadData *td = new threadData(s);

        pthread_create(&tid, nullptr, threadroutine, td);
        tids.push_back(tid);
        // sleep(1);
    }
    sleep(1);
    // cout << "main thread get a new thread mesg:" << *p << ",&p:" << p << endl;
    // for (int i = 0; i < NUM; i++)
    // {
    //     pthread_join(tids[i], nullptr);
    // }
    while (true)
    {
        cout << "i am a main thread" << endl;
        sleep(1);
    }
    return 0;
}